//
//  BaseFillViewController.mv
//  CarCare
//
//  Created by ileo on 14-8-30.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "BaseInputViewController.h"

@interface BaseInputViewController () 

@property (nonatomic, assign) TYPE_INPUT inputType;

@end

@implementation BaseInputViewController

- (instancetype)init
{
    self = [self initWithInputType:TYPE_INPUT_SCROLLVIEW];
    if (self) {
        self.textFields = [NSMutableArray arrayWithCapacity:3];
    }
    return self;
}

-(id)initWithInputType:(TYPE_INPUT)type{
    TYPE_MAIN_VIEW mainViewType = (type == TYPE_INPUT_TABLEVIEW ? TYPE_MAIN_VIEW_TABLE_NORMAL : TYPE_MAIN_VIEW_SCROLL_NORMAL);
    self = [super initWithMainViewType:mainViewType];
    if (self) {
        self.inputType = type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.scrollView.contentSize = CGSizeMake(__MAIN_WIDTH, __MAIN_HEIGHT);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChangedNotification:) name:UITextFieldTextDidChangeNotification object:nil];
    
    switch (self.inputType) {
        case TYPE_INPUT_SCROLLVIEW:
        {
            UIButton *button = [[UIButton alloc] initWithFrame:self.view.frame];
            [button addTarget:self action:@selector(clickOnBG) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollView addSubview:button];
        }
            break;
        case TYPE_INPUT_TABLEVIEW:
        {
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            self.tableView.showsHorizontalScrollIndicator = NO;
            self.tableView .showsVerticalScrollIndicator = NO;
            
//            UIPanGestureRecognizer * hidenPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(clickOnBG)];
//            [self.tableView addGestureRecognizer:hidenPan];
//            UITapGestureRecognizer * hidenPan = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickOnBG)];
//            [self.tableView addGestureRecognizer:hidenPan];
            
        }
            break;
        default:
            break;
    }
    
    // Do any additional setup after loading the view.
}

-(void)clickOnBG{
   	[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

-(UITextField *)textFieldWithFrame:(CGRect)frame type:(TEXTFIELD_TYPE)type{
    UITextField *textField = [ViewFactory textFieldWithFrame:frame type:type hasBG:NO inView:self.scrollView];
    textField.delegate = self;
    [self.textFields addObject:textField];
    return textField;
}

-(void)registerTextField:(UITextField *)textField{
    [self.textFields addObject:textField];
    textField.delegate = self;
}

#pragma mark - textDelegate
-(void)textFieldTextChangedNotification:(NSNotification *)notification{
    [self textFieldTextChanged:(UITextField *)(notification.object)];
}
-(void)textFieldTextChanged:(UITextField *)textField{}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self textFieldWillDidEndEditing:textField];
}
-(void)textFieldWillDidEndEditing:(UITextField *)textField{}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    BOOL hasNull = NO;
    for (UITextField *tf in self.textFields) {
        if (![tf.text isNotNil]) {
            hasNull = YES;
            break;
        }
    }
    if(!hasNull) [self clickOnKeyBoardDone];
    return !hasNull;
}

-(BOOL)textFieldCanAddString:(NSString *)string withTextField:(UITextField *)textField{
    return YES;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL hasNull = NO;
    if (![string isNotNil] && textField.text.length == 1) {
        hasNull = YES;
    }else{
        for (UITextField *tf in self.textFields) {
            if (![tf.text isNotNil]) {
                if (tf != textField || ![string isNotNil]) {
                    hasNull = YES;
                    break;
                }
            }
        }
    }
    [self textFieldTextHasNull:hasNull];
    if ([string isNotNil] && ![self textFieldCanAddString:string withTextField:textField]) {
        return NO;
    }
    if (textField.text.length > [self textFieldMaxNumberWithTextField:textField] && [string isNotNil]) {
        [AlertMgr showShortNormalTextTips:@[@"输入过长"]];
        return NO;
    }
    return YES;
}
-(BOOL)allTextFieldTextHasNull{
    for (UITextField *tf in self.textFields) {
        if (![tf.text isNotNil]) {
            return YES;
        }
    }
    return NO;
}
-(NSInteger)textFieldMaxNumberWithTextField:(UITextField *)textField{
    return 64;
}
-(void)textFieldTextHasNull:(BOOL)null{}
-(void)clickOnKeyBoardDone{
}

#pragma mark - keyboard
- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    [self keyBoardWillShow];
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [self moveViewWhenKeyBoardChangeToHeight:CGRectGetHeight(keyboardRect) WithDuiation:animationDuration];
}
-(void)keyBoardWillShow{}
- (void)keyboardDidShow:(NSNotification *)notification {
}
- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self moveViewWhenKeyBoardChangeToHeight:0 WithDuiation:animationDuration];
}
-(void)moveViewWhenKeyBoardChangeToHeight:(CGFloat)height WithDuiation:(NSTimeInterval)duration{
}

#pragma mark - tableView
#pragma mark - tableView delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self tableViewWithTableView:tableView cellForRowAtIndexPath:indexPath];
}

#pragma mark - tableview 可重写方法 本身不实现
-(void)tableViewNewCell:(UITableViewCell *)cell textField:(void(^)(NSInteger tagNum))textField Label:(void(^)(NSInteger tagNum))label
{
}
- (void)tableViewGetCell:(UITableViewCell *)cell cellForRowAtIndexPath:(NSIndexPath *)indexPath textField:(UITextField *(^)(NSInteger tagNum))textField Label:(UILabel *(^)(NSInteger tagNum))label;
{
}
-(UITextField *)textFieldWithTag:(NSInteger)tagNum withCellIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UITextField * textField = (UITextField *)[cell viewWithTag:tagNum];
    return textField;
}
- (UITableViewCell *)tableViewWithTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSString * cellID = [NSString stringWithFormat:@"%zd-%zd",indexPath.section,indexPath.row];
    static NSString *cellID = @"cellID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        [self tableViewNewCell:cell textField:^(NSInteger tagNum) {
            UITextField * textField = [Factory textFieldWithFrame:CGRectZero hideText:NO defaultText:@"" onView:cell];
            textField.font = FONT_DEFAULT_Light(14);
            textField.textAlignment = NSTextAlignmentLeft;
            textField.hidden = YES;
            textField.tag = tagNum;
            [self registerTextField:textField];
        } Label:^(NSInteger tagNum) {
            UILabel * leftLabel = [Factory labelWithFrame:CGRectZero font:FONT_DEFAULT_Light(14) text:@"" textColor:[Theme wordColor] onView:cell textAlignment:NSTextAlignmentLeft];
            leftLabel.tag = tagNum;
        }];
    }
    
    [self tableViewGetCell:cell cellForRowAtIndexPath:indexPath textField:^UITextField *(NSInteger tagNum) {
        UITextField * textField = (UITextField *)[cell viewWithTag:tagNum];
        return textField;
        
    } Label:^UILabel *(NSInteger tagNum) {
        UILabel * leftLabel = (UILabel *)[cell viewWithTag:tagNum];
        return leftLabel;
    }];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UILabel *)labelWithTag:(NSInteger)tagNum withCellIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UILabel  * label= (UILabel *)[cell viewWithTag:tagNum];
    return label;
}

@end
